<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建宣讲设置' : "编辑宣讲设置" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="专家" prop="expertId">
          <el-select v-model="ruleForm.expertId" placeholder="请选择专家" filterable>
            <el-option v-for="(sItem, sIndex) in expertList" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否接受推送" prop="isAcceptPush">
          <el-radio-group v-model="ruleForm.isAcceptPush" class="ml-4">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否接受预约" prop="isAcceptAppointment">
          <el-radio-group v-model="ruleForm.isAcceptAppointment" class="ml-4">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="可预约时间" prop="week">
          <el-radio-group @change="weekChange" v-model="weekCheck">
            <el-radio label="monday">周一</el-radio>
            <el-radio label="tuesday">周二</el-radio>
            <el-radio label="wednesday">周三</el-radio>
            <el-radio label="thursday">周四</el-radio>
            <el-radio label="friday">周五</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="可预约时间段" prop="timeCheckList">
          <el-checkbox-group v-model="timeCheckList" :disabled="!weekCheck" @change="timeChange">
            <el-checkbox :label="1">上午场</el-checkbox>
            <el-checkbox :label="2">下午场</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCourseSettingAdd" }
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getCourseSettingDetail()
  }

  getExpertList()
  /* 如果是从专家列表跳转过来，默认选中此专家 */
  if(route.currentRoute.value.query.expertId){
    ruleForm.value.expertId = route.currentRoute.value.query.expertId
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getCourseSettingDetail = () => {
  loading.value = true
  http.$GET("/PreachM/GetPreachExpertCourseSettingDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    const weeks = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']

    /* 处理日期时段 */
    for (let index = 0; index < weeks.length; index++) {
      const week = weeks[index];
      const morning = ruleForm.value[`${week}MorningStatus`]
      const afternoon = ruleForm.value[`${week}AfternoonStatus`]
      if (morning) {
        weekCheck.value = week
        timeCheckList.value.push(1)
      }
      if (afternoon) {
        weekCheck.value = week
        timeCheckList.value.push(2)
      }
      if (morning || afternoon) break
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 专家下拉列表请求 */
const expertList = ref([])
const expertPageIndex = ref(1)
const expertPageSize = ref(1000)

const getExpertList = () => {
  let params = {
    pageIndex: expertPageIndex.value,
    pageSize: expertPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetExpertInfoList`, params).then(res => {
    expertList.value = expertList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      expertPageIndex.value = expertPageIndex.value + 1
      getExpertList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 表单 */
const ruleFormRef = ref(null)

/* 周 */
const weekCheck = ref('')

/* 时段 */
const timeCheckList = ref([])

/* 表单数据 */
const ruleForm = ref({
  id: "",
  expertId: "",
  mondayMorningStatus: false,
  mondayAfternoonStatus: false,
  tuesdayMorningStatus: false,
  tuesdayAfternoonStatus: false,
  wednesdayMorningStatus: false,
  wednesdayAfternoonStatus: false,
  thursdayMorningStatus: false,
  thursdayAfternoonStatus: false,
  fridayMorningStatus: false,
  fridayAfternoonStatus: false,
  isAcceptPush: null,
  isAcceptAppointment: null,
})

/* 表单校验规则 */
const rules = reactive({
  expertId: [
    { required: true, message: '请选择专家', trigger: 'change' }
  ],
  isAcceptPush: [
    { required: true, message: '请选择是否接受推送', trigger: 'change' }
  ],
  isAcceptAppointment: [
    { required: true, message: '请选择是否接受预约', trigger: 'change' }
  ],
})

const weekChange = () => {
  /**设置上下午选中状态 */
  timeCheckList.value.length = 0
  ruleForm.value[`${weekCheck.value}MorningStatus`] && timeCheckList.value.push(1)
  ruleForm.value[`${weekCheck.value}AfternoonStatus`] && timeCheckList.value.push(2)
}

const timeChange = () => {
  /**存入数据 */
  ruleForm.value[`${weekCheck.value}MorningStatus`] = timeCheckList.value.includes(1)
  ruleForm.value[`${weekCheck.value}AfternoonStatus`] = timeCheckList.value.includes(2)
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      http.$POST("/PreachM/AddOrUpdatePreachExpertCourseSettingInfo", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');
          route.push({
            path: "/backend/publicize-courseSetting"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/publicize-courseSetting",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>